package com.aaron.sqlSession;

import com.aaron.config.BoundSql;
import com.aaron.pojo.Configuration;
import com.aaron.pojo.MappedStatement;
import com.aaron.utils.GenericTokenParser;
import com.aaron.utils.ParameterMapping;
import com.aaron.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


public class SimpleExecutor implements Executor {

    private PreparedStatement getPreparedStatement(Connection connection, MappedStatement mappedStatement, BoundSql boundSql, Object... params) throws Exception {
        //4. 获取预处理对象： preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //5. 设置参数
        //获取请求参数返回参数实体的全路径
        getParameterType(mappedStatement, boundSql, preparedStatement, params);

        return preparedStatement;
    }

    private void getParameterType(MappedStatement mappedStatement, BoundSql boundSql, PreparedStatement preparedStatement, Object[] params) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, SQLException {
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappingsList = boundSql.getParameterMappingsList();

        for (int i = 0; i < parameterMappingsList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingsList.get(i);
            //参数值
            String content = parameterMapping.getContent();
            //反射

            if ("java.lang.Integer".equals(parameterClass.getName())){
                preparedStatement.setObject(i + 1, params[0]);
            }else {
                Field declaredField = parameterClass.getDeclaredField(content);
                declaredField.setAccessible(true);
                Object o = declaredField.get(params[0]);
                preparedStatement.setObject(i + 1, o);
            }


        }
    }

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //1. 注册驱动，获取连接
        Connection connection = getConnection(configuration);
        //2. 获取sql语句
        //3.加载参数替换sql语句中的占位符
        BoundSql boundSql = getBoundSql(mappedStatement);
        //4.处理sql
        PreparedStatement preparedStatement = getPreparedStatement(connection, mappedStatement, boundSql, params);
        //6. 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
//        System.out.println(preparedStatement.ge);
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<>();

        //7. 封装返回结果
        while (resultSet.next()) {
            Object o = resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);
                //使用反射，根据数据库表和实体的对应关系，完成封装
                try {
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(o, value);
                } catch (Exception e) {
                    //未找到相关字段跳过
                }


            }
            objects.add(o);
        }

        return (List<E>) objects;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null) {
            return Class.forName(parameterType);
        }
        return null;
    }

    /**
     * 完成对#{}的解析工作：1.将#{}使用？进行代替，2.解析出#{}里面的值进行存储
     *
     * @param sql 需要处理的sql语句
     * @return BoundSql
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类：配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        //#{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(parseSql, parameterMappings);


    }

    /**
     * 注册驱动
     * @return Connection
     */
    private Connection getConnection(Configuration configuration) throws SQLException {
        //1. 注册驱动，获取连接
        return configuration.getDataSource().getConnection();
    }

    /**
     * 获取sql 并替换占位符
     *
     * @param mappedStatement mappedStatement
     * @return BoundSql
     */
    private BoundSql getBoundSql(MappedStatement mappedStatement) {
        //2. 获取sql语句
        //3.加载参数替换sql语句中的占位符
        return getBoundSql(mappedStatement.getSql());
    }

    public Integer insertOrUpdateOrDelete(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception {
        //创建数据库连接
        Connection connection = configuration.getDataSource().getConnection();
        //获取sql语句
        String sql = mappedStatement.getSql();
        //拼接sql
        BoundSql boundSql = getBoundSql(sql);
        //4. 获取预处理对象： preparedStatement
        PreparedStatement preparedStatement = getPreparedStatement(connection, mappedStatement, boundSql, params);
        //5. 设置参数
        getParameterType(mappedStatement, boundSql, preparedStatement, params);
        System.out.println(boundSql.getSqlText());
        //执行sql
        preparedStatement.executeUpdate();
        return preparedStatement.getUpdateCount();
    }
}
